package ch.bfh.abhmcm.SoftwareEngineeringAndDesign.controller.exportRFC;

import java.sql.ResultSet;
import java.util.ArrayList;

import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.controller.RFCMaker;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.controller.database.DatabaseConnection;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.model.RFC;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.view.mainframe.exportRFCPanel.ExportRFCPanel;

public class GenerateListThread extends Thread {

	private ExportRFCPanel exportRFCPanel;
	private DatabaseConnection connection;

	public GenerateListThread(ExportRFCPanel exportRFCPanel) {

		this.exportRFCPanel = exportRFCPanel;

	}

	@Override
	public void run() {

		this.connection = new DatabaseConnection();
		this.connection.connect();
		String selectedItem = exportRFCPanel.getFunctionPanel().getSelectBox()
				.getSelectedItem().toString();

		this.exportRFCPanel.getListPanel().getDisplayTable().clearTable();

		String query;

		if (selectedItem.equals("Alle")) {
			query = "SELECT * FROM CMS_RFC";

		} else if (selectedItem.equals("Eigene")) {

			String name = exportRFCPanel.getMainframe().getSignedInUser()
					.getFirstname()
					+ " "
					+ exportRFCPanel.getMainframe().getSignedInUser().getName();

			query = "SELECT * FROM CMS_RFC WHERE " + RFC.TC_RFCINITIATOR
					+ " = '" + name + "'";

		} else {

			query = "SELECT * FROM CMS_RFC WHERE " + RFC.TC_Status + " = '"
					+ selectedItem + "'";
		}

		ResultSet rs = connection.query(query);

		int count = 0;

		ArrayList<RFC> list = new ArrayList<RFC>();

		try {
			while (rs.next()) {
				count++;

				RFCMaker maker = new RFCMaker();

				list.add(maker.makeanRFC(rs));
			}

			if (count == 0) {

				this.exportRFCPanel.getListPanel().getDisplayTable()
						.displayNoElenemt();
				this.exportRFCPanel.getFunctionPanel().getExportButton()
						.setEnabled(false);

			} else {

				// visible is a cheat
				this.exportRFCPanel.getListPanel().getDisplayTable()
						.setVisible(false);
				for (RFC rfc : list) {
					this.exportRFCPanel.getListPanel().getDisplayTable()
							.addRFCinTable(rfc);
				}
				this.exportRFCPanel.getListPanel().getDisplayTable()
						.setVisible(true);
				this.exportRFCPanel.getFunctionPanel().getExportButton()
						.setEnabled(true);
			}

		} catch (Exception e) {

			System.out.println("wrong query");
		}

		this.exportRFCPanel.getFunctionPanel().getProgress().setVisible(false);
		this.exportRFCPanel.getListPanel().getDisplayTable().setEnabled(true);
		this.exportRFCPanel.getListPanel().getDisplayTable().revalidate();
		connection.disconnect();
	}
}
